package com.cherrypt.api.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class MailUtils {
    private static final Logger logger = LoggerFactory.getLogger(MailUtils.class);

    public static void sendActivationEmail(String to, String activationUrl) {
        send(to, CherryUtils.config.getEmailSubject(), CherryUtils.config.getEmailActivationTemplate()
                .replaceAll("\\?url", activationUrl));
    }

    public static void sendInviteEmail(String to, String inviteUrl) {
        send(to, CherryUtils.config.getEmailSubject(), CherryUtils.config.getEmailInviteTemplate()
                .replaceAll("\\?url", inviteUrl));
    }

    public static void sendResetPassEmail(String to, String resetUrl) {
        send(to, CherryUtils.config.getEmailSubject(), CherryUtils.config.getEmailResetPassTemplate()
                .replaceAll("\\?url", resetUrl));
    }

    public static void send(String to, String subject, String body) {
        Properties props = System.getProperties();
        props.put("mail.smtp.host", CherryUtils.config.getEmailSmtpHost());
        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.ssl.enable", "true");
        Session session = Session.getDefaultInstance(props, null);
        // 置true可以在控制台（console)上看到发送邮件的过程
        session.setDebug(true);
        // 用session对象来创建并初始化邮件对象
        MimeMessage mimeMsg = new MimeMessage(session);
        Multipart mp = new MimeMultipart();
        try {
            mimeMsg.setFrom(new InternetAddress(
                    CherryUtils.config.getEmailName(), CherryUtils.config.getEmailNickName(), "UTF-8"));
            mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            mimeMsg.setSubject(subject);
            BodyPart bp = new MimeBodyPart();
            bp.setContent(body, "text/html;charset=UTF-8");
            // 在组件上添加邮件文本
            mp.addBodyPart(bp);
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            logger.info("正在发送邮件....");
            Transport transport = session.getTransport("smtp");
            // 连接邮件服务器并进行身份验证
            transport.connect(CherryUtils.config.getEmailSmtpHost(), CherryUtils.config.getEmailSmtpPort(),
                    CherryUtils.config.getEmailName(), CherryUtils.config.getEmailPass());
            // 发送邮件
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
            logger.info("发送邮件成功！");
            transport.close();
        } catch (MessagingException | UnsupportedEncodingException e) {
            logger.error("邮件发送错误，to: " + to + " subject: " + subject + " body: " + body, e);
        }
    }
}
